package com.CTAtracker.android.Fragments;

import java.util.ArrayList;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.CTAtracker.android.R;
import com.CTAtracker.android.Activities.SlidingActivity;
import com.CTAtracker.android.Activities.StationActivity;
import com.CTAtracker.android.Adapters.SearchAdapter;
import com.CTAtracker.android.Models.Station;

public class SearchFragment extends Fragment {

	/**
	 * The SearchView of the fragment
	 */
	private TextView _searchTextView; 
	/**
	 * List of station matching the name
	 */
	private ArrayList<Station> _listStation;
	/**
	 * The list view containing the result of the search 
	 */
	private ListView _listViewSearch;
	/**
	 * The adapter for the list of search station
	 */
	private SearchAdapter _searchAdapter;
	/**
	 * Listener on the list view. Retrieve the Station selected and display the new Activity
	 */
	private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
		public void onItemClick(AdapterView parent, View v, int position, long id) {

			Intent intent = new Intent((SlidingActivity)getActivity(), StationActivity.class);
			intent.putExtra("idStation", _listStation.get(position).getStationId());
			intent.putExtra("lineId", _listStation.get(position).get_line_id());
			startActivity(intent);
		}
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		_listStation = new ArrayList<Station>();
		return inflater.inflate(R.layout.search_fragment, container, false);
	}

	@Override
	public void onStart() {
		super.onStart();
		_searchTextView = (TextView) getActivity().findViewById(R.id.searchTextView);
		_listViewSearch = (ListView) getActivity().findViewById(R.id.searchListView);

		_searchAdapter = new SearchAdapter(
				getActivity(), R.layout.search_fragment_row, _listStation);
		_listViewSearch.setAdapter(_searchAdapter);
		
		// Listeners
		_listViewSearch.setOnItemClickListener(mMessageClickedHandler);
		_searchTextView.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable s) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				_searchAdapter.updateListView(s.toString());
			}
		}); 
	}
}
